//groovy -cp "/d/apps/jboss5/client/jbossall-client.jar:/d/apps/jboss5/common/lib/jboss-javaee.jar" scripts/sendToQueue.groovy  "/queue/ExampleQueue" "Test"
//@Grab(group='org.jboss.naming', module='jnp-client', version='5.0.4.GA')
class SendToQueue {

	Object withJNDIContext(java.util.Map userProps = [:], Closure closure) {
		def props = new Properties()
		props.setProperty('java.naming.factory.initial', 'org.jnp.interfaces.NamingContextFactory')
		props.setProperty('java.naming.factory.url.pkgs', 'org.jboss.naming:org.jnp.interfaces')
		props.setProperty('java.naming.provider.url', 'jnp://localhost:1099')
		props.putAll(userProps)
		def ctx = new javax.naming.InitialContext(props)
		try {
			closure.call(ctx)
		} finally {
			ctx.close()
		}
	}		
	
	Object withConnection(Closure closure) {
		def cf = withJNDIContext { ctx -> ctx.lookup("ConnectionFactory") }
		def conn = cf.createConnection()
		try {
			closure.call(conn)
		} finally {
			conn.close()
		}
	}
	
	Object withDestination(String destName, Closure closure) {
		def (dest, cf) = withJNDIContext { ctx -> [ctx.lookup(destName), ctx.lookup("ConnectionFactory")] }
		def conn = cf.createConnection()
		try {
			// create a non-transactional and auto acknowledge received messages session.
			def session = conn.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE)
			conn.start()
			closure.call(dest, session)
			session.close()
			conn.stop()
		} finally {
			conn.close()
		}
	}
	
	Object withProducer(String queueName, Closure closure) {		
		withDestination(queueName) { queue, session ->
			def producer = session.createProducer(queue)
			closure.call(producer, session)
		}
	}
	
	String text
	String queueName
	
	void run() {
		withProducer(queueName) { producer, session ->
			def txtmsg = session.createTextMessage(text)
			producer.send(txtmsg)
		}
	}
	
}

// main
main = new SendToQueue()
main.queueName = args[0]
main.text = args[1]
main.run()